package com.github.binarywang.demo.wx.mp.service;

import com.github.binarywang.demo.wx.mp.beans.WxMpUser;
import com.github.binarywang.demo.wx.mp.jpa.WxMpUserDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
@ComponentScan(basePackages = "com.github.binarywang.demo.wx.mp.beans.WxMpUser")
public class LsWxMpUserService {
    @Autowired
    private WxMpUserDao wxMpUserDao;

    public Boolean add(WxMpUser user){
        user.setCreateTime(new Date());
        if(user.getOpenId()!=null){
            String openIds =user.getOpenId();
            user.setOpenIds(openIds);
        }
        return wxMpUserDao.save(user).getId()>0;
    }

    public Boolean update(WxMpUser user){
        user.setUpdateTime(new Date());
        return wxMpUserDao.save(user).getId()>0;
    }

    public Boolean addOrUpdate(WxMpUser mpUser) {
        WxMpUser mpUserServer = null;
        if (StringUtils.isNotBlank(mpUser.getUnionId())){
            mpUserServer = getByUnionId(mpUser.getUnionId());
        }
        if (mpUserServer==null){
            mpUserServer = getByLikeOpenId(mpUser.getOpenId());
        }
        if (mpUserServer==null){
            mpUserServer = getByBasicInfo(WxMpUser.basic(mpUser));
        }

        if (mpUserServer != null) {
            mpUserServer.setNickname(mpUser.getNickname());
            mpUserServer.setHeadimgUrl(mpUser.getHeadimgUrl());
            mpUserServer.setProvince(mpUser.getProvince());
            mpUserServer.setCity(mpUser.getCity());
            mpUserServer.setCountry(mpUser.getCountry());
            mpUserServer.setSex(mpUser.getSex());
            String openIds = mpUserServer.getOpenIds();
            if (openIds==null){
                openIds = mpUser.getOpenId();
            }else{
                openIds+=","+mpUser.getOpenId();
            }
            mpUserServer.setOpenIds(openIds);
            return update(mpUserServer);
        }
        return add(mpUser);
    }

    public WxMpUser getByBasicInfo(WxMpUser basic) {
        return wxMpUserDao.findOne(Example.of(basic)).orElse(null);
    }

    public WxMpUser getByLikeOpenId(String openId) {
        return wxMpUserDao.findByOpenIdsLike("%"+openId+"%");
    }

    public WxMpUser getByUnionId(String unionId) {
        return wxMpUserDao.findOne(Example.of(WxMpUser.builder().unionId(unionId).build())).orElse(null);
    }
}
